package com.mxpio.erp.technology.service.impl;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.plm.entity.ProjectInfo;
import com.mxpio.erp.common.technology.entity.BomInfoLine;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.entity.ProductFinalizationReview;
import com.mxpio.erp.common.technology.service.ProductFinalizationReviewService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class ProductFinalizationReviewServiceImpl extends BaseServiceImpl<ProductFinalizationReview> implements ProductFinalizationReviewService {
    @Override
    @Transactional
    public Result<ProductFinalizationReview> auditPass(String code, String result) {
        ProductFinalizationReview review = this.getById(ProductFinalizationReview.class, code);
        if (review==null){
            return Result.error("code未匹配到数据");
        }
        if (StringUtils.equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode(),result)){
            Item one = JpaUtil.getOne(Item.class, review.getItemCode());
            one.setLifeCycle("D");
            JpaUtil.update(one);
            review.setBpmnStatus( OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
        }else{
            review.setBpmnStatus( OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode());
        }
        update(review);
        return Result.OK(review);
    }

    @Override
    @Transactional
    public ProductFinalizationReview getByIdWith(String code) {
        return JpaUtil.linq(ProductFinalizationReview.class)
                .collect("itemCode", Item.class,"itemCode")
                .collect("proCode", ProjectInfo.class,"proCode")
                .equal("code",code).findOne();
    }

    @Override
    @Transactional
    public Result<ProductFinalizationReview> add(ProductFinalizationReview review) {
        Long bomlineCount = JpaUtil.linq(BomInfoLine.class).equal("itemCode", review.getItemCode()).count();
        if (bomlineCount>0){
            return Result.error("当前数据非产品，不能进行评审");
        }
        Long count = JpaUtil.linq(ProductFinalizationReview.class).equal("itemCode", review.getItemCode()).equal("bpmnStatus", OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode()).count();
        if (count>0){
            return Result.error("已经有审核中的定型评审申请，请勿重复提交");
        }
        Item item = JpaUtil.getOne(Item.class, review.getItemCode());
        if (!item.getLifeCycle().equals("S")){
            return Result.error("产品生命周期发生变化，不满足申请条件：S");
        }
        this.save(review);
        return Result.OK(review);
    }
}
